<?php

namespace app\common\model\user;

use app\common\model\User;
use think\Model;


class Log extends Model
{





    // 表名
    protected $name = 'user_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'state_text',
        'paytime_text'
    ];



    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function puser()
    {
        return $this->belongsTo('app\common\model\User', 'p_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function group()
    {
        return $this->belongsTo('Group', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function addLog($data, $userInfo, $pay_type)
    {
        if ($userInfo->group_id > $data->level) {
            exception('当前等级大于购买等级');
        }
        if ($userInfo->group_id == 1) {
            $p_id = $userInfo->pid;
            $p_interests = $data->p_interests;
        } else {
            $p_interests = 0;
        }
        $res = self::create([
            'user_id' => $data->user_id,
            'sn' => sn('user_log', 'sn', 'UL'),
            'group_id' => $data->level,
            'pay_money' => $data->price,
            'interests' => $data->interests,
            'dividend' => $data->dividend,
            'p_id' => $p_id,
            'p_interests' => $p_interests,
            'paytime' => time(),
            'pay_type' => $pay_type,
        ]);
        if ($res) {
            return $res;
        } else {
            exception('下单失败');
        }
    }
}
